package com.changgou.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.util.FastDFSClient;
import com.changgou.util.FastDFSFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file) {

        try {
            String orgFileName = file.getOriginalFilename();

            int index = orgFileName.lastIndexOf(".");

            String extName = orgFileName.substring(index);

            byte[] content = file.getBytes();

            FastDFSFile fastDFSFile = new FastDFSFile(orgFileName, content, extName);

            String[] uploadResult = FastDFSClient.upload(fastDFSFile);

            String groupName = uploadResult[0];
            String remoteFileName = uploadResult[1];
            String url = FastDFSClient.getTrackerUrl() + groupName + "/" + remoteFileName;
            logger.info("上传成功!url:{}", url);

            return new Result(true, StatusCode.OK, "上传成功", url);

        } catch (IOException e) {
            e.printStackTrace();
            logger.info("上传失败!");
            return new Result(false, StatusCode.ERROR, "上传失败");
        }


    }
}
